import 'package:flutter/material.dart';
import 'package:hello_flutter/demo/error/post_change_notifier.dart';
import 'package:provider/provider.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ChangeNotifierProvider(
        builder: (_) => PostChangeNotifier(),
        child: HomePage(),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        centerTitle: true,
        title: Text('错误❌处理模拟'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Consumer<PostChangeNotifier>(
              builder: (_, notifier, __) {
                if (notifier.state == NotifierState.initial) {
                  return CustomTxT('请点击下方按钮重试👇');
                } else if (notifier.state == NotifierState.loading) {
                  return CircularProgressIndicator();
                } else {
                  if (notifier.failure != null) {
                    return CustomTxT(notifier.failure.message);
                  } else {
                    return CustomTxT('${notifier.post}');
                  }
                }
              },
            ),
            RaisedButton(
              child: Text('获取帖子🔘'),
              onPressed: () async =>
                  Provider.of<PostChangeNotifier>(context).getOnePost(),
            )
          ],
        ),
      ),
    );
  }
}

class CustomTxT extends StatelessWidget {
  CustomTxT(this.text);
  final String text;

  @override
  Widget build(BuildContext context) => Text(
        text,
        textAlign: TextAlign.center,
        style: TextStyle(fontSize: 32.0),
      );
}
